package com.cb2.algorithm.leetcode;

/**
 * <a href="https://leetcode.cn/problems/spiral-matrix-ii">螺旋矩阵 II(Spiral Matrix II)</a>
 * <p>给你一个正整数n，生成一个包含 1 到 n^2 所有元素，且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix。</p>
 *
 * <p>
 * <b>示例：</b>
 * <pre>
 *  示例1：
 *      输入：n = 3
 *      输出：[[1,2,3],[8,9,4],[7,6,5]]
 *
 *  示例 2：
 *      输入：n = 1
 *      输出：[[1]]
 * </pre>
 * </p>
 *
 * <p>
 * <b>提示：</b>
 * <ul>
 *     <li>1 <= n <= 20</li>
 * </ul>
 * </p>
 *
 * @author c2b
 * @since 2025/2/7 9:49
 */
public class LC0059Spiral_Matrix_II_M {

    static class Solution {
        public int[][] generateMatrix(int n) {
            // l、r、t、b：左、右、上、下边界
            int l = 0;
            int r = n - 1;
            int t = 0;
            int b = n - 1;
            int num = 1;
            int end = n * n;
            int[][] matrix = new int[n][n];
            while (num <= end) {
                // 从左上到右上，行不变，列增加
                for (int i = l; i <= r; i++) {
                    matrix[t][i] = num++;
                }
                ++t;
                // 从上右到右下，行减小，列不变
                for (int i = t; i <= b; i++) {
                    matrix[i][r] = num++;
                }
                --r;
                // 从右下到左下，行不变，列减小
                for (int i = r; i >= l; i--) {
                    matrix[b][i] = num++;
                }
                --b;
                // 从左下到左上，行增加，列不变
                for (int i = b; i >= t; i--) {
                    matrix[i][l] = num++;
                }
                ++l;
            }
            return matrix;
        }
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        int times = 4;
        for (int t = 1; t <= times; t++) {
            for (int[] nums : solution.generateMatrix(t)) {
                System.out.print("[");
                for (int i = 0; i < nums.length; i++) {
                    System.out.printf("%0" + String.valueOf(t * t).length() + "d", nums[i]);
                    if (i != nums.length - 1) {
                        System.out.print(",");
                    }
                }
                System.out.println("]");
            }
            System.out.println("-------------");
        }
    }
}
